package com.wangsong.system.controller;

import com.wangsong.common.controller.BaseController;
import com.wangsong.common.model.CodeEnum;
import com.wangsong.common.model.Result;
import com.wangsong.system.entity.User;
import com.wangsong.system.service.ILoginService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.stream.Collectors;

@RestController
@ControllerAdvice
public class LoginController extends BaseController {

    @Autowired
    private ILoginService loginService;

    @RequestMapping(value = "/index")
    public Result index() {
        return Result.success(CodeEnum.INDEX.getCode(), null);
    }


    @RequestMapping(value = "/login")
    public Result loginPost(@Valid @RequestBody User user) {
        String data = loginService.loginPost(user);
        return Result.success(data);
    }


    @ExceptionHandler(value = Exception.class)
    public Result illegalArgumentException(Exception e) {
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String string = bindingResult.getFieldErrors().stream().map(
                fieldError -> fieldError.getDefaultMessage()
        ).collect(Collectors.joining());
        return Result.error(CodeEnum.NO_NULL.getCode(), string);
    }
}
